package com.xls.boxlibrary.risk;

import android.annotation.SuppressLint;
import android.webkit.ValueCallback;

import androidx.appcompat.app.AppCompatActivity;

import com.xls.boxlibrary.utils.AppUtils;
import com.xls.boxlibrary.utils.SPUtils;
import com.xls.commonlibrary.BuildConfig;
import com.xls.commonlibrary.http.Api;
import com.xls.commonlibrary.http.Result;
import com.xls.commonlibrary.http.RetrofitHelper;
import com.xls.commonlibrary.http.RxLifecycle;
import com.xls.commonlibrary.http.Transformer;
import com.xls.commonlibrary.util.AESUtil;
import com.xls.commonlibrary.util.SysDataUtil;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Nonnull;

public class RiskEncodeUtil {
    private static volatile RiskEncodeUtil singleton = null;

    private RiskEncodeUtil() {
    }

    public static RiskEncodeUtil getInstance() {
        if (singleton == null) {
            synchronized (RiskEncodeUtil.class) {
                if (singleton == null) {
                    singleton = new RiskEncodeUtil();
                }
            }
        }
        return singleton;
    }

    ///////////////////////////////////////////////////////

    @SuppressLint("CheckResult")
    public void riskCheck(
            @Nonnull AppCompatActivity activity,
            String source,
            Map<String, String> stringStringMap,
            @Nonnull ValueCallback<Result> callback
    ) {

        stringStringMap.put("appName", AppUtils.getPackageName(activity));
        stringStringMap.put("token", SPUtils.getLoginToken(activity));
        stringStringMap.put("source", source);


        Map<String, String> data = new LinkedHashMap<>();
        data.put("mdKey", AESUtil.httpRequestProcess(stringStringMap, source));
        // 数据太多需要放到IO线程中貌似
        data.put("apps", SysDataUtil.getInstance().getPkgList());

        String url = BuildConfig.BASE_COM_URL_BOX + "api/user/fkCheck";

        RetrofitHelper.getInstance()
//        GetUrlUtil.getInstance()
                .create(Api.class)
                .fkCheck(url, data)
                .compose(Transformer.transform())
                .compose(RxLifecycle.bindRxLifecycle(activity))
                .subscribe(
                        result -> {
                            if (callback != null) {
                                callback.onReceiveValue(result);
                            }
                        },
                        throwable -> {

                        }
                );
    }
}
